import 'package:star_author/config/ui_constant.dart';
import 'package:star_author/utils/common_util/num_util.dart';
import 'package:star_author/utils/common_util/toast/custom_toast.dart';
import 'package:star_author/utils/http/http_util.dart';
import 'package:star_author/utils/rouces_util.dart';
import 'package:star_author/widgets/cover_widget.dart';
import 'package:star_author/widgets/empty_view/v_empty_view.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get_navigation/get_navigation.dart';
import 'package:get/state_manager.dart';

import '../../../utils/utils.dart';

///评论主播
class EvaluateAnchorBottomSheet extends StatefulWidget {
  final int studiosId;
  final Map studioDetailMap;
  final bool isEdit;

  const EvaluateAnchorBottomSheet(
    this.studiosId,
    this.studioDetailMap, {
    Key? key,
    this.isEdit = false,
  }) : super(key: key);

  @override
  State<EvaluateAnchorBottomSheet> createState() =>
      _EvaluateAnchorBottomSheetState();
}

class _EvaluateAnchorBottomSheetState extends State<EvaluateAnchorBottomSheet> {
  String textFiledString = '';

  double rate = 0;

  String info = "";

  @override
  void initState() {
    rate = widget.studioDetailMap['living_anchor']?['good_rate'] ?? 0;
    info = widget.studioDetailMap['living_anchor']?['introduction'] ?? "";

    if (widget.isEdit == false &&
        widget.studioDetailMap['living_anchor']['review'] != null) {
      textFiledString =
          widget.studioDetailMap['living_anchor']['review']['comment'];
      getEvaluate(
          widget.studioDetailMap['living_anchor']['review']['evaluate'] ?? "");
    }

    setState(() {});
    super.initState();
  }

  TextStyle style = TextStyle(
    fontSize: 14.sp,
    color: rgba(102, 102, 102, 1),
  );

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: () {
        FocusScope.of(context).requestFocus(FocusNode());
      },
      child: Container(
        width: double.infinity.w,
        child: Stack(
          children: [
            Container(
                padding: EdgeInsets.symmetric(
                  horizontal: 12.w,
                  vertical: 12.w,
                ),
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.vertical(
                    top: Radius.circular(16.w),
                  ),
                ),
                child: SingleChildScrollView(
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.start,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      Row(
                        mainAxisAlignment: MainAxisAlignment.start,
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          buildCircleCover(
                              size: 52.w,
                              cover: widget.studioDetailMap['living_anchor']
                                      ?['avatar'] ??
                                  ''),
                          SizedBox(
                            width: 6.w,
                          ),
                          Text(
                            "${widget.studioDetailMap['living_anchor']?['nickname'] ?? '主播大熊'}",
                            style: TextStyle(
                              fontSize: 16.sp,
                              color: UIConstant.color33,
                              fontWeight: FontWeight.w500,
                            ),
                          ),
                          SizedBox(
                            width: 6.w,
                          ),
                          Container(
                            height: 16.w,
                            decoration: BoxDecoration(
                              color: rgba(255, 95, 95, 1),
                              borderRadius: BorderRadius.circular(2.w),
                            ),
                            child: Row(
                              children: [
                                Container(
                                  width: 36.w,
                                  height: 16.w,
                                  child: Stack(
                                    children: [
                                      Image.asset(
                                        RoucesUtil.getAssets(
                                            'ic_evaluate_rate_lt'),
                                        width: 36.w,
                                        height: 16.w,
                                      ),
                                      Container(
                                        padding: EdgeInsets.only(
                                          left: 2.w,
                                        ),
                                        alignment: Alignment.centerLeft,
                                        child: Text(
                                          "好评率",
                                          style: TextStyle(
                                            fontSize: 10.sp,
                                            color: rgba(224, 32, 32, 1),
                                            fontWeight: FontWeight.w500,
                                          ),
                                        ),
                                        width: 36.w,
                                        height: 16.w,
                                      ),
                                    ],
                                  ),
                                ),
                                Container(
                                  margin: EdgeInsets.only(
                                    left: 2.w,
                                    right: 2.w,
                                  ),
                                  alignment: Alignment.centerLeft,
                                  child: Text(
                                    "${NumUtil.multiply(rate, 100)}%",
                                    style: TextStyle(
                                      fontSize: 10.sp,
                                      color: Colors.white,
                                      fontWeight: FontWeight.w500,
                                    ),
                                  ),
                                ),
                              ],
                            ),
                          ),
                        ],
                      ),
                      if (info.isNotEmpty)
                        Container(
                          margin: EdgeInsets.symmetric(
                            horizontal: 12.w,
                            vertical: 10.w,
                          ),
                          padding: EdgeInsets.symmetric(
                            horizontal: 12.w,
                            vertical: 12.w,
                          ),
                          child: Builder(builder: (context) {
                            TextPainter painter = getTextPainter(context, info,
                                style, Get.width - 24.w - 24.w - 24.w, 8);
                            Widget text = Text(
                              info,
                              style: style,
                            );
                            if (painter.computeLineMetrics().length >= 8) {
                              return Container(
                                height:
                                    painter.computeLineMetrics()[0].height * 8,
                                child: SingleChildScrollView(
                                  child: text,
                                ),
                              );
                            } else {
                              return text;
                            }
                          }),
                          decoration: BoxDecoration(
                            color: rgba(255, 250, 238, 1),
                            borderRadius: BorderRadius.circular(8.w),
                          ),
                        ),
                      buildResultOrEditView(),
                    ],
                  ),
                )),
          ],
        ),
      ),
    );
  }

  Widget buildResultOrEditView() {
    if (widget.isEdit) {
      return Column(
        mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          VEmptyView(13.w),
          Text(
            "为主播本场直播进行评价",
            style: TextStyle(
              fontSize: 12.sp,
              color: UIConstant.color99,
              fontWeight: FontWeight.w500,
            ),
          ),
          VEmptyView(13.w),
          Container(
            alignment: Alignment.center,
            child: buildScoreStarWidget(),
          ),
          VEmptyView(14.w),
          Container(
            width: 350.w,
            height: 80.w,
            decoration: BoxDecoration(
              color: UIConstant.colorF8F8,
              borderRadius: BorderRadius.all(
                Radius.circular(8.w),
              ),
            ),
            alignment: Alignment.topLeft,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.end,
              children: [
                Expanded(
                  flex: 1,
                  child: TextField(
                    cursorColor: Color(0xffFEBA07),
                    decoration: InputDecoration(
                      hintText: '留下您对主播的意见和反馈，我们将做得更好',
                      hintStyle: TextStyle(
                        fontSize: 12.sp,
                        color: UIConstant.color99,
                      ),
                      contentPadding: EdgeInsets.only(
                        left: 10.w,
                        right: 10.w,
                        top: 10.w,
                        bottom: 0,
                      ),
                      border: InputBorder.none,
                      counterText: '',
                      isDense: true,
                    ),
                    style: TextStyle(
                      fontSize: 14.sp,
                      color: UIConstant.color66,
                    ),
                    maxLength: 100,
                    maxLines: null,
                    textInputAction: TextInputAction.send,
                    onChanged: (val) {
                      if (mounted) {
                        textFiledString = val;
                        setState(() {});
                      }
                    },
                  ),
                ),
                Text(
                  "${textFiledString.length}/100",
                  style: TextStyle(
                    fontSize: 12.sp,
                    color: UIConstant.color99,
                  ),
                ),
                VEmptyView(6.w),
              ],
            ),
          ),
          VEmptyView(20.w),
          GestureDetector(
            behavior: HitTestBehavior.opaque,
            onTap: () {
              submit();
            },
            child: Container(
              width: 350.w,
              height: 44.w,
              decoration: BoxDecoration(
                color: Color(0xffFEBA07),
                borderRadius: BorderRadius.all(
                  Radius.circular(1000),
                ),
              ),
              alignment: Alignment.center,
              child: Text(
                "提交",
                style: TextStyle(
                  fontSize: 16.sp,
                  fontWeight: FontWeight.w500,
                  color: Colors.white,
                ),
              ),
            ),
          ),
        ],
      );
    } else {
      return Padding(
        padding: EdgeInsets.symmetric(
          horizontal: 12.w,
          vertical: 18.w,
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Container(
              child: Stack(
                clipBehavior: Clip.none,
                children: [
                  Row(
                    children: [
                      Text(
                        "本场直播已评价：",
                        style: TextStyle(
                          fontSize: 12.sp,
                          color: UIConstant.color99,
                        ),
                      ),
                      VEmptyView(10.w),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          RoucesUtil.getAssetsIcon(
                              data[currentIndex]['select_image'], 25),
                          SizedBox(
                            width: 8.w,
                          ),
                          Text(
                            data[currentIndex]['title'],
                            style: TextStyle(
                              fontSize: 16.sp,
                              color: rgba(255, 148, 10, 1),
                            ),
                          ),
                        ],
                      ),
                    ],
                  ),
                  Positioned(
                    child: RoucesUtil.getAssetsIcon(
                        'ic_evaluated_anchor_score_lt', 72),
                    right: 0,
                    top: -20,
                  )
                ],
              ),
            ),
            VEmptyView(20.w),
            Text(
              textFiledString,
              style: TextStyle(
                fontSize: 14.sp,
                color: UIConstant.color66,
              ),
            ),
          ],
        ),
      );
    }
  }

  List data = [
    {
      "image": "ic_well_lt",
      "select_image": "ic_select_well_lt",
      "title": "好评",
    },
    {
      "image": "ic_middle_lt",
      "select_image": "ic_select_middle_lt",
      "title": "中评",
    },
    {
      "image": "ic_bad_lt",
      "select_image": "ic_select_bad_lt",
      "title": "差评",
    },
  ];

  getEvaluate(String evaluate) {
    if (evaluate == "bad") {
      currentIndex = 2;
    } else if (evaluate == "middle") {
      currentIndex = 1;
    } else if (evaluate == "good") {
      currentIndex = 0;
    }
  }

  int currentIndex = 0;

  Widget buildScoreStarWidget() {
    return Container(
      width: Get.width,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: List.generate(
          data.length,
          (index) => Container(
            width: (110 / 375) * Get.width,
            height: 40.w,
            margin: EdgeInsets.only(
              right: index == data.length - 1 ? 0 : 10.w,
            ),
            child: GestureDetector(
              behavior: HitTestBehavior.opaque,
              onTap: () {
                if (!widget.isEdit) {
                  return;
                }
                setState(() {
                  currentIndex = index;
                });
              },
              child: Container(
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    RoucesUtil.getAssetsIcon(
                        currentIndex == index
                            ? data[index]['select_image']
                            : data[index]['image'],
                        25),
                    SizedBox(
                      width: 8.w,
                    ),
                    Text(
                      data[index]['title'],
                      style: TextStyle(
                        fontSize: 16.sp,
                        color: currentIndex == index
                            ? rgba(255, 148, 10, 1)
                            : rgba(182, 182, 182, 1),
                      ),
                    ),
                  ],
                ),
                decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(
                      6.w,
                    ),
                    border: Border.all(
                      color: currentIndex == index
                          ? rgba(255, 148, 10, 1)
                          : rgba(182, 182, 182, 1),
                      width: 1,
                    )),
              ),
            ),
          ),
        ),
      ),
    );
  }

  //description: '0-差评 1-中评 2-好评' }
  void submit() {
    int evaluate = 0;
    if (currentIndex == 0) {
      evaluate = 2;
    } else if (currentIndex == 1) {
      evaluate = 1;
    } else if (currentIndex == 2) {
      evaluate = 0;
    }
    HttpUtil.commonRequest(
      Get.context!,
      "/api/v1/studios/${widget.studiosId}/anchor_reviews/${widget.studioDetailMap['living_anchor']['id']}",
      method: HttpUtil.MethodPost,
      data: {
        // 'stars': evaluate,
        'comment': textFiledString,
        "evaluate": evaluate,
      },
      isLoading: true,
    ).then((value) async {
      CustomToast.show("提交成功，感谢您的评价");
      await Future.delayed(Duration(milliseconds: 300));
      Get.back(result: true);
    });
  }
}
